﻿using System;
using System.Linq;
using System.Windows.Controls;
using MahApps.Metro.Controls;
using System.Windows.Media;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
using ACC.Extensions.ClientBusiness.PLC;
using ACC.Extensions.ClientBusiness;
using ACC.Extensions.PCClient.Helper;
using ACC.Extensions.Utilities;
using ACC.Extensions.Entities;
using ACC.Extensions.PCClient.UserControls;
using System.Collections;
using System.Collections.Generic;
using ACC.Extensions.PCClient.View;
using System.Data;
using System.Windows.Input;
using System.Windows;
using ACC.Data.Entities.Common;
using ACC.Data.Entities.Mes;


namespace ACC.Extensions.PCClient.BaseWindow
{
    public partial class BaseCustomWindow : MetroWindow
    {
        private object _lockObj = new object();
        //与ACC通讯端口
        protected int inAccPort;
        //Lite库Helper对象
        protected ClientSqlLite clientSqlLite;
        //和ACC通信的Socket对象
        protected AccSocketServer accSocketServer;
        //PLC进程对象
        protected SiemensPlcProcess plcProcess = null;
        //ACC进程对象
        public static AccProcess accProcess;
        //是否与ACC建立连接
        protected bool bIsAccConnected;
        // 连接虚拟PLC
        protected string debugMode;

        protected BaseCustomWindow()
        {
            clientSqlLite = new ClientSqlLite();
        }

        //创建ACC进程对象
        protected void CreateAccProcess()
        {
            accProcess = ScriptHelper.CreateAccProcess();
            if (accProcess == null)
            {
                accProcess = new AccProcess();
            }
        }

        //启动Socketserver监听ACC的连接
        protected void CreateAccSocketServer(ListView lvwMsg)
        {
            try
            {
                ShowMessage(lvwMsg, LanguageHelper.LoadStringFromResource("MSG_START_SOCKET_SERVER"), false);

                //第一步是需要和ACC建立Socket连接
                if (accSocketServer == null)
                {
                    accSocketServer = new AccSocketServer(inAccPort);
                    ShowMessage(lvwMsg, LanguageHelper.LoadStringFromResource("MSG_SOCKET_SERVER_STARTED"), false);

                    //与ACC建立连接后事件
                    accSocketServer.OnAccConnected += AccSocketServerConnected;
                    ////与ACC断开连接后事件
                    accSocketServer.OnAccDisconnected += AccSocketServerDisconnected;

                    ////通过ACC获取配置
                    accSocketServer.OnClientConfigChanged += AccSocketServerConfigChanged;
                    accSocketServer.OnChangeover += AccSocketServerChangeover;
                    accSocketServer.OnOperatorChanged += AccSocketServerOperatorChanged;
                    accSocketServer.OnLotTrackChanged += FillLotTrack;
                    accSocketServer.OnWISChanged += FillWIS;
                    accSocketServer.OnIssueChanged += FillIssue;
                    accSocketServer.OnShiftChanged += FillShift;
                    accSocketServer.OnReceivedGBSN +=ReceivedGBSN;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(lvwMsg, string.Format(LanguageHelper.LoadStringFromResource("MSG_CLIENT_STARTUP_ERROR"), ex.Message), true);
                Log4Helper.Error("Start Client Error: ", ex);
            }
        }

        //lvMessage列表添加消息
        protected void ShowMessage(ListView lvMessage, string msg, bool isError)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return;
            }
            string shownMsg = String.Format("[{0}]: {1}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg);
            //Log4Helper.Debug(shownMsg);

            Dispatcher.Invoke(new Action(() =>
            {
                if (lvMessage.Items.Count > 200)
                {
                    lvMessage.Items.Remove(lvMessage.Items[lvMessage.Items.Count - 1]);
                }
                ListViewItem item = new ListViewItem();
                item.Content = shownMsg;
                item.VerticalContentAlignment = VerticalAlignment.Center;

                if (isError)
                {
                    item.Foreground = new SolidColorBrush(Colors.White);
                    item.Background = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    item.Foreground = new SolidColorBrush(Colors.Black);
                    item.Background = new SolidColorBrush(Colors.LightGray);
                }
                lvMessage.Items.Insert(0, item);
            }));
        }

        /// <summary>
        /// 连接上ACC服务器后需要做的一些事
        /// </summary>
        public virtual void AccSocketServerConnected()
        {
        }

        /// <summary>
        /// 与ACC断开连接
        /// </summary>
        public virtual void AccSocketServerDisconnected()
        {
        }

        /// <summary>
        /// 表示接受到ACC发过来的配置信息
        /// </summary>
        public virtual void AccSocketServerConfigChanged()
        {
        }

        /// <summary>
        /// 接收到ACC换型通知时所做的事情
        /// </summary>
        public virtual void AccSocketServerChangeover(ClientPartType partType)
        {
        }

        /// <summary>
        /// 操作工登陆后填充页面
        /// </summary>
        public virtual void AccSocketServerOperatorChanged(ClientOperator oper)
        {
        }

        public virtual void FillLotTrack(List<ClientLotTrackItem> lots)
        {
        }

        public virtual void FillWIS(List<MESWI> wis)
        {
        }

        public virtual void FillIssue(List<MESIssue> issues)
        {
        }

        public virtual void ReceivedGBSN(string gbsn)
        {
        }

        public virtual void FillShift(ClientShiftCfg csc)
        { }

        /// <summary>
        /// 更新设备状态
        /// </summary>
        /// <param name="strDeviceName"></param>
        /// <param name="bIsConnected"></param>
        public virtual void UpdateDeviceStatus(string strDeviceName, bool bIsConnected)
        {
        }

        //连接PLC后
        public virtual void PLCConnected()
        {
        }

        // 客户端输出信息
        public virtual void ClientPrint(string strData, string strMsg, bool isWarning)
        {
        }

        //PLC监控的事件
        protected void PlcProcessTrigger(int eventType, bool value)
        {
            switch (eventType)
            {
                case 4:
                    LoadRequestPLC();
                    break;
                case 5:
                    UnloadRequestPLC();
                    break;
                case 6:
                    MaterialInRequestPLC(1);      // 上料1
                    break;
                case 7:
                    MaterialOutRequestPLC(1);     // 下料1
                    break;
                case 8:
                    MaterialInRequestPLC(2);      // 上料2
                    break;
                case 9:
                    MaterialOutRequestPLC(2);     // 下料2
                    break;
                case 10:
                    MaterialInRequestPLC(3);      // 上料3
                    break;
                case 11:
                    MaterialOutRequestPLC(3);     // 下料3
                    break;
                case 12:
                    MaterialInRequestPLC(4);      // 上料4
                    break;
                case 13:
                    MaterialOutRequestPLC(4);     // 下料4
                    break;
                case 14:
                    MaterialCoreInRequestPLC();     // 三大件叫料
                    break;
                default:
                    break;
            }
        }

        public virtual void BeginPrintPLC()
        {

        }

        public virtual void PrintLabelPLC()
        {
        }

        public virtual void LoadRequestPLC()
        {
        }

        public virtual List<string> GetScannedBarcodes()
        {
            return new List<string>();
        }

        public virtual void UnloadRequestPLC()
        {
        }

        public virtual void MaterialInRequestPLC(int portNo)
        {
        }

        public virtual void MaterialOutRequestPLC(int portNo)
        {
        }

        public virtual void MaterialCoreInRequestPLC()
        {
        }

        public virtual void SendBarcodeToMachine()
        {
        }

        public virtual void GetCncPlcDataEvent()
        {
        }

        public virtual void SendCncRepairDataEvent()
        {
        }

        public virtual void GetRealTimePlcDataEvent(int eventType)
        {
        }

        protected ClientResponse SendLoadRequest(List<string> barcodes, List<ClientProcData> processDatas = null)
        {
            return accProcess.Load(barcodes, UISession.CurrentPartType == null ? 0 : UISession.CurrentPartType.PartTypeId, processDatas);
        }

        protected void AutoChangModelbyPartType(ClientPartType partType, ListView lvwMsg)
        {
            try
            {
                lock (_lockObj)
                {
                    //通知ACC进行换型
                    //根据PartType进行换型，获取相应的参数
                    UISession.CurrentPartType = partType;
                    string msg = String.Empty;
                    UISession.CurrentPartTypeData = accProcess.ChangeModel(partType.PartTypeId, out msg);


                    if (!String.IsNullOrEmpty(msg))
                    {
                        ShowMessage(lvwMsg, String.Format("{0}:{1}", LanguageHelper.LoadStringFromResource("TITLE_ERR_CHANGEOVER"), msg),
                            true);
                    }
                    else
                    {
                        ShowMessage(lvwMsg, String.Format(LanguageHelper.LoadStringFromResource("MSG_CANGEOVER_COMPLETED"),
                        UISession.CurrentPartType.PartNo), false);
                    }

                }
            }
            catch (Exception ex)
            {
                Log4Helper.Error("ClientSocket_OnChangeover error: ", ex);
            }
        }
        protected bool AccUnload(string strBarcode, List<ClientProcData> listProcData, UnloadVariable unloadData, int statusBits, ListView lvwMsg)
        {
            try
            {
                string msg = String.Empty;
                List<string> listBarcode = new List<string>() { strBarcode };
                var unloadResult = SendUnloadRequest(listBarcode, listProcData, unloadData, statusBits, 0);
                if (!unloadResult.Result)
                {
                    ShowMessage(lvwMsg, String.Format("{0}:{1},{2}", strBarcode, LanguageHelper.LoadStringFromResource("MSG_ACC_UNLOAD_FAILD"), unloadResult.Message), true);
                    UnloadRetry(listBarcode, listProcData, 1, unloadResult.Message);
                }
                else
                {
                    ShowMessage(lvwMsg, string.Format("{0}:{1}", strBarcode, LanguageHelper.LoadStringFromResource("MSG_ACC_UNLOAD_SUCCESS")), false);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log4Helper.Error("ACC Unload Error: ", ex);
            }

            return false;
        }

        protected bool? UnloadRetry(List<string> lstStrBarcode, List<ClientProcData> lstProcessData, int inBit, string strMsg)
        {
            LoadUnloadRetryWnd wnd = new LoadUnloadRetryWnd(
                RetryType.Unload, lstStrBarcode, accProcess, inBit, strMsg, lstProcessData);
            bool? dialogResult = wnd.ShowDialog();
            return dialogResult;
        }

        protected ClientResponse SendUnloadRequest(List<string> listBarcode, List<ClientProcData> listProcData, UnloadVariable unlodaData, int statusBit, int failureBits)
        {
            return accProcess.Unload(listBarcode, listProcData, unlodaData, statusBit,failureBits, UISession.CurrentPartType == null ? 0 : UISession.CurrentPartType.PartTypeId);
        }

        protected void TextBoxIsNum_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        protected void TextBoxIsNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {

        }

        protected void TextBoxIsNum_Pasting(object sender, DataObjectPastingEventArgs e)
        {

        }
    }
}
